/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { useState, useRef, useEffect } from 'react' // ract内置属性
import './index.css' // 页面样式
import { useNavigate } from 'react-router-dom' // 路由引入
import { NavBar, Button, Picker, Toast, Popup, List, Switch } from 'antd-mobile' // UI组件引入
import MusicProgress from './progress' // 音乐进度条组件
import { DownOutline, LeftOutline, SetOutline } from 'antd-mobile-icons' // 页面icon
// import { onLoadAudio } from '../../../../utils/audio' // 音频可视化函数 // 暂时去除
import paly from '../../../../assets/music/play.png' // 播放图标
import pause from '../../../../assets/music/pause.png' // 暂停图标
import { getMusic } from '../../../../api/index' // 获取音乐数据
import { useDispatch, useSelector } from "react-redux" // redux引入
import axios from 'axios' // 请求为了重定向转流播放




/* ts定义 */
type CascadePickerOption = {
  label: string
  value: string
  children?: CascadePickerOption[]
}

interface IMusic {
  auther: string,
  id: number,
  name: string,
  pic_url: string,
  url: string
}

function MyMuisc() {

  /* 路由 */
  const navigate = useNavigate()

  /* 声明变量 */
  const typeList: CascadePickerOption[] = [
    { label: "热歌榜", value: '热歌榜' },
    { label: "新歌榜", value: '新歌榜' },
    { label: "飙升榜", value: '飙升榜' },
    { label: "原创榜", value: '原创榜' },
  ] // 音乐类型
  const [typeName, setTypeName] = useState<(string | null)>('热歌榜') // 音乐类型榜单名字
  const [typeVisible, setTypeVisible] = useState<boolean>(false) // 音乐类型弹窗
  const [palyShow, setPalyShow] = useState<boolean>(true) // 播放还是暂停 true为播放 false为暂停
  const [musicInfo, setMusicInfo] = useState<IMusic | null>(null) // 音乐信息
  const [percent, setPercent] = useState<number>(0) // 音频进度条
  const [duration, setDuration] = useState<number>(0) // 音频总时长
  const [currentTime, setCurrentTime] = useState(0); // State 来保存当前播放时间
  const [upVisible, setUpVisible] = useState<boolean>(false) // 设置弹窗
  const audioRef = useRef<HTMLAudioElement>(null) // 音频标签
  const rotateRef = useRef<HTMLDivElement>(null) // 旋转容器
  const settingMusicRef = useRef<any>(null);


  /* redux */
  const settingMusic = useSelector((state: any) => state.music) // 获取音乐设置
  const dispatch = useDispatch<any>() // 声明dispatch


  /* 事件函数 */
  // 获取音乐数据
  const getMusicData = async () => {
    onpause()
    try {
      Toast.show({
        icon: 'loading',
        content: '音乐加载中…',
        duration: 0,
      })
      const res = await getMusic(typeName, { type: 'json' })
      setMusicInfo(res.data.info)
      const prefix = 'https://music.163.com/';
      const extracted = res.data.info.url.substring(prefix.length)
      const axiosConfig: any = {
        method: 'get',
        maxRedirects: 0,
        url: `/api/${extracted}`,
        responseType: 'arraybuffer' // 指定响应类型为 arraybuffer
      };
      axios(axiosConfig)
        .then(response => {
          console.log(response);
          const blob = new Blob([response.data], { type: 'audio/mp3' });
          if (audioRef.current) audioRef.current.src = URL.createObjectURL(blob);
          Toast.clear()
          if (settingMusicRef.current.isAutoNext) {
            onplay();
          }
        })
        .catch(error => {
          console.error('获取音频数据时出错:', error);
        });
      console.log(res);
    } catch (error) {
      Toast.clear()
      console.log(error);

    }
  }
  // 播放音乐
  const onplay = () => {
    audioRef.current?.play()
    setPalyShow(false)
    if (rotateRef.current) rotateRef.current.style.animationPlayState = 'running';
    // onLoadAudio(audioRef.current) // 暂时去除
    // 监听音频播放事件
    let lastCheckedTime = -1;
    audioRef.current?.addEventListener('timeupdate', function () {
      // 获取当前音频播放的时间（以秒为单位）
      const NewCurrentTime: any = audioRef.current?.currentTime;
      // 只在整数秒时执行逻辑
      if (Math.floor(NewCurrentTime) !== lastCheckedTime) {
        lastCheckedTime = Math.floor(NewCurrentTime);
        setCurrentTime(lastCheckedTime)
        const percentage: any = (lastCheckedTime / duration * 100).toFixed(2)
        console.log(percentage)
        setPercent(percentage)

      }
    });
  }
  // 暂停音乐
  const onpause = () => {
    setPalyShow(true)
    audioRef.current?.pause()
    if (rotateRef.current) rotateRef.current.style.animationPlayState = 'paused';
  }
  // 切换歌曲
  const onSwitch = () => {
    setPalyShow(true)
    audioRef.current?.pause()
    if (rotateRef.current) rotateRef.current.style.animationPlayState = 'paused';
    getMusicData()
  }
  // 从指定时间开始播放
  const handleSeek = (time: number) => {
    if (audioRef.current) {
      audioRef.current.currentTime = time;
      setCurrentTime(time);
    }
  };
  // 当音频元素加载完毕后，获取音乐的总时长
  const handleLoadedData = () => {
    const audioElement = audioRef.current;
    if (audioElement) {
      setDuration(audioElement.duration); // 设置总时长到状态变量中
    }
  };
  // 子组件修改进度条时间
  const onChangeProgress = (e: any) => {
    const newProgress = e.toFixed(2)
    console.log(newProgress);
    const newCurrentTime = (newProgress / 100) * duration;
    setPercent(e)
    setCurrentTime(newCurrentTime);
    handleSeek(newCurrentTime)
  }

  /* 用于加载数据 */
  useEffect(() => {
    getMusicData()
    // 定义处理音频结束事件的函数
    const handleAudioEnd = () => {
      onpause()
      if (settingMusicRef.current?.isCirculate){
        onplay()
        setPercent(0)
        return
      }
      setPalyShow(true)
      getMusicData()
      // 在这里可以执行其他的结束后的操作，例如重新播放或显示相关信息
    };

    // 监听音频结束事件
    if (audioRef.current) audioRef.current.addEventListener('ended', handleAudioEnd);

    // 清除副作用以及清除事件监听
    return () => {
      // eslint-disable-next-line react-hooks/exhaustive-deps
      if (audioRef.current) audioRef.current.removeEventListener('ended', handleAudioEnd);
    };

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [typeName]);

  useEffect(() => {
    console.log(settingMusic);
    settingMusicRef.current = settingMusic;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [settingMusic]);


  return (
    <>
      <div className="muisc-container">
        <NavBar backIcon={<LeftOutline color='#fff' fontSize={26} />} right={<SetOutline onClick={() => setUpVisible(true)} color='#fff' fontSize={26} />} onBack={() => navigate(-1)}></NavBar>
        {/* 顶部选项榜单 */}
        <div className='muisc-top' onClick={() => { setTypeVisible(true) }}>
          <span>{typeName}</span>
          <DownOutline color='#fff' />
          <Picker
            columns={[typeList]}
            visible={typeVisible}
            onClose={() => { setTypeVisible(false) }}
            value={[typeName]}
            onConfirm={(value) => setTypeName(value[0] as string)}
          />
        </div>
        <div className='needle-ab'></div>
        <div className='muisc-center' ref={rotateRef}>
          <img src={musicInfo?.pic_url} alt="" />
        </div>
        <div className='muisc-title'>
          <h3>{musicInfo?.name}</h3>
          <p>{musicInfo?.auther}</p>
        </div>
        {/* 音频标签 */}
        <audio ref={audioRef} controls crossOrigin="anonymous" style={{ display: 'none' }} src="" onLoadedData={handleLoadedData} ></audio>
        {/* canvas绘制音浪 暂时去除 */}
        {/* <canvas id="canvas"></canvas> */}
        {/* 音频进度条 */}
        <MusicProgress duration={duration} percent={percent} currentTime={currentTime} onChildClickProgress={(e) => { onChangeProgress(e) }}></MusicProgress>
        {/* 播放 暂停 */}
        <div className='muisc-setting'>
          {
            palyShow ? <img onClick={onplay} src={paly} alt="" /> : <img onClick={onpause} src={pause} alt="" />
          }
        </div>
        {/* 底部下载 切换 */}
        <div className='muisc-footer'>
          <Button style={{ width: '48%' }} color='primary' fill='outline' shape='rounded'>
            下载歌曲
          </Button>
          <Button style={{ width: '48%' }} color='danger' shape='rounded' onClick={onSwitch}>切换歌曲</Button>
        </div>
      </div>
      {/* 弹窗设置 */}
      <Popup
        visible={upVisible}
        onMaskClick={() => {
          setUpVisible(false)
        }}
        onClose={() => {
          setUpVisible(false)
        }}
      >
        <List header='功能设置'>
          <List.Item extra={<Switch style={{
            '--checked-color': '#00b578',
            '--height': '30px',
            '--width': '50px',
          }} checked={settingMusic.isCirculate} onChange={(val) => dispatch.music.updataCirculate(val)} />}>单曲循环</List.Item>
          <List.Item extra={<Switch style={{
            '--checked-color': '#00b578',
            '--height': '30px',
            '--width': '50px',
          }} checked={settingMusic.isAutoNext} onChange={(val) => dispatch.music.updataAutoNext(val)} />}>自动下一首</List.Item>
        </List>
      </Popup>
    </>
  );
}

export default MyMuisc;